#!/bin/env python3
# -*- encoding=utf8 -*-
#******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# Author: wangchong
# Create: 2021-07-09
# ******************************************************************************

"""
osc co project packages and rename
"""


import os
import sys
import shutil
from concurrent.futures import ThreadPoolExecutor

class obs(object):
    def __init__(self, **kwargs):
        self.kwargs = kwargs
        self.proj = self.kwargs["proj"]
        self.pkglistfile = self.kwargs["pkglistfile"]
        self.co_path = ""

    def create_dir(self):
        self.co_path = os.path.join(os.getcwd(), "osc_co")
        if os.path.exists(self.co_path):
           shutil.rmtree(self.co_path)
        os.makedirs(self.co_path)
    
    def osc_co_pkg(self, pkg):
        """
        osc co a package
        """
        _tmpdir = os.popen("mktemp -d").read().strip('\n')
        cmd = "cd %s && osc co %s %s &>/dev/null && cd - &>/dev/null" % (_tmpdir, self.proj, pkg)
        ret = os.popen(cmd).read()
        proj_tmpdir = os.path.join(_tmpdir, self.proj)
        if not os.path.exists(proj_tmpdir):
            print("failed to exec cmd: %s" % (cmd))
            shutil.rmtree(_tmpdir)
            return -1
        pkg_tmpdir = os.path.join(proj_tmpdir, pkg)
        if os.path.exists(pkg_tmpdir):
            cmd = "cd %s && osc up -S &>/dev/null && rename _service:tar_scm_kernel_repo: '' _service:tar_scm_kernel_repo:* && rm -f _service && cd - &>/dev/null" % pkg_tmpdir
            if os.system(cmd) != 0:
                print("Failed to rename %s file." % pkg)
            cmd = "cp %s %s -rf" % (pkg_tmpdir, self.co_path)
            if os.system(cmd) == 0:
                print("Succeed to osc co %s and rename file and bakup." % pkg)
            else:
                print("Failed to bakup %s file." % pkg)
        else:
            print("Failed to osc co %s." % pkg)
        shutil.rmtree(_tmpdir)

    def co_all_packages(self):
        file_msg = []
        if os.path.exists(self.pkglistfile):
            self.create_dir()
            data = open(self.pkglistfile, "r")
            for line in data:
                file_msg.append(line.strip('\n'))
            data.close()
        else:
            print("%s is not exits." % self.pkglistfile)
            return -1
        with ThreadPoolExecutor(20) as job:
            for pkg in file_msg:
                job.submit(self.osc_co_pkg, pkg)

if __name__ == "__main__":
    if len(sys.argv) == 3:
        kw = {"proj": sys.argv[1], "pkglistfile":sys.argv[2]}
        obs = obs(**kw)
        obs.co_all_packages()
    else:
        print("Please check parameter, you should run as: python3 %s projectname pkglistfile" % sys.argv[0])
